﻿using System;
using System.Web.UI;
using BLL;
using DAL;
using Ext.Net;
using System.Data;
using Roles;

namespace ERP.Modules
{
    public partial class Order : UserControl
    {
        #region[Define]
        private static bool _flag;
        #endregion

        #region[Controller]
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                CheckPermisstion();
                txtDateBegin.Text = DateTime.Now.ToString();
                txtDateBeginPay.Text = DateTime.Now.ToString();
                txtDateEndPay.Text = DateTime.Now.ToString();
                txtPaymentDate.Text = DateTime.Now.ToString();
                GetOrder();
                btnEdit.Disable(true);
                btnDel.Disable(true);
                btnExport.Disable(true);
                btnReview.Disable(true);
            }
        }
        //Store
        protected void StoreOrder_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtSearch.Text = string.Empty;
            SelectBoxReview.Text = string.Empty;
            SelectBoxIsUsed.Text = string.Empty;
            txtDateBeginFillter.Text = string.Empty;
            txtDateEndFillter.Text = string.Empty;
            GetOrder();
        }
        protected void StoreOrder_Detail_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            if (_flag)
            {
                GetOrderDetailTemp();
                GetOrderDetailTempSum();
            }
            else
            {
                if (String.IsNullOrEmpty(txtOrder_ID.Text))
                {
                    HTML.clsFormat.Alert_ERROR("Lỗi", "Có lỗi xảy ra trong quá trình tải lại !");
                }
                else
                {
                    GetOrderEdit(int.Parse(txtOrder_ID.Text));
                    GetOrderSum(int.Parse(txtOrder_ID.Text));
                }
            }

        }
        protected void StoreOrderReview_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            if (String.IsNullOrEmpty(txtIDReview.Text))
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", "Có lỗi xảy ra trong quá trình tải lại !");
            }
            else
            {
                GetOrderReview(int.Parse(txtIDReview.Text));
            }
        }
        protected void StoreMaterial_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            GetMaterials();
        }
        protected void StoreCustomerOrder_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            GetCustomer();
        }
        //Button
        protected void btnAddNew_Click(object sender, DirectEventArgs e)
        {
            _flag = true;
            btnRefreshOrderCode.Enable(true);
            btnAddCustomer.Enable(true);
            btnAddMaterial.Enable(true);
            btnDelMaterial.Enable(true);
            ClearText();
            GetAutoID();
            WindowsOrder.Show();
        }
        protected void btnEdit_Click(object sender, DirectEventArgs e)
        {
            var sm = grOrder.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (var row in sm.SelectedRows)
                {
                    _flag = false;
                    txtOrderCode.ReadOnly = true;
                    btnRefreshOrderCode.Disable(true);
                    int Order_Id = int.Parse(row.RecordID);
                    GetOrderEdit(Order_Id);
                    GetOrderSum(Order_Id);
                    WindowsOrder.Show();
                }
        }
        protected void btnDel_Click(object sender, DirectEventArgs e)
        {
            try
            {
                var sm = grOrder.GetSelectionModel() as CheckboxSelectionModel;
                if (sm != null)
                    foreach (var row in sm.SelectedRows)
                    {
                        var obj = new EtOrder { Order_Id = int.Parse(row.RecordID) };
                        BllOrder.Delete(obj);
                        if (obj.Msg == 0)
                            HTML.clsFormat.Alert_ERROR("Lỗi", "Có chứng từ liên quan,không thể xoá !");
                        if (obj.Msg == 2)
                            HTML.clsFormat.Alert_ERROR("Lỗi", "Chứng từ đã được xét duyệt không thể xoá được !");
                        if (obj.Msg == 3)
                            HTML.clsFormat.Alert_ERROR("Lỗi", "Có chứng từ liên quan,không thể xoá !");
                    }
                GetOrder();
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        protected void btnReview_Click(object sender, DirectEventArgs e)
        {
            var sm = grOrder.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (var row in sm.SelectedRows)
                {
                    _flag = false;
                    int Order_Id = int.Parse(row.RecordID);
                    GetOrderReview(Order_Id);
                    GetOrderSum(Order_Id);
                    WindowOrderReview.Show();
                }
        }
        protected void btnFillter_Click(object sender, DirectEventArgs e)
        {
            GetOrderFillterDate();
        }
        protected void btnSavePopUp_Click(object sender, DirectEventArgs e)
        {
            Insert();
        }
        protected void btnAddMaterial_Click(object sender, DirectEventArgs e)
        {
            var sm = grMaterial.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null) sm.DeselectAll();
            GetMaterials();
            WindowMaterial.Show();
        }
        protected void btnDelMaterial_Click(object sender, DirectEventArgs e)
        {
            if (_flag)
            {
                var sm = grOrder_Detail.GetSelectionModel() as CheckboxSelectionModel;
                if (sm != null)
                    foreach (var row in sm.SelectedRows)
                    {
                        try
                        {
                            DeleteDetail(int.Parse(row.RecordID), 1);
                        }
                        catch (Exception)
                        {
                            HTML.clsFormat.Alert_ERROR("Thông Báo",
                                "Tồn tại tài liệu con, không xoá được vui lòng xoá tài liệu con trước !");
                        }
                    }
                GetOrderDetailTemp();
            }
            else
            {
                var sm = grOrder_Detail.GetSelectionModel() as CheckboxSelectionModel;
                if (sm != null)
                    foreach (var row in sm.SelectedRows)
                    {
                        try
                        {
                            DeleteDetail(int.Parse(row.RecordID), 0);
                        }
                        catch (Exception)
                        {
                            HTML.clsFormat.Alert_ERROR("Thông Báo", "Tồn tại tài liệu con, không xoá được vui lòng xoá tài liệu con trước !");
                        }
                    }
                GetOrderEdit(int.Parse(txtOrder_ID.Text));
            }
        }
        protected void btnCancelPopUp_Click(object sender, DirectEventArgs e)
        {
            ClearText();
            WindowsOrder.Close();
        }
        protected void btnRefreshOrderCode_Click(object sender, DirectEventArgs e)
        {
            GetAutoID();
        }
        protected void btnAddCustomer_Click(object sender, DirectEventArgs e)
        {
            var sm = grCustomerOrder.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null) sm.DeselectAll();
            GetCustomer();
            WindowCustomerOrder.Show();
        }
        protected void btnSelectMaterial_Click(object sender, DirectEventArgs e)
        {
            if (_flag)
            {
                InsertDetail();
            }
            else
            {
                UdpateDetail();
            }
        }
        protected void btnReviewWindow_Click(object sender, DirectEventArgs e)
        {
            try
            {
                var obj = new EtOrderDetail
                {
                    Order_Id = int.Parse(txtIDReview.Text),
                    IsActive = true,
                    Users_Id_Review = int.Parse(Session["Users_Id"].ToString())
                };
                BllOrder.Review(obj);
                HTML.clsFormat.Alert_INFO("Thông Báo", "Xét duyệt đơn hàng thành công !");
                GetOrder();
                GetOrderReview(int.Parse(txtIDReview.Text));
                GetOrderSum(int.Parse(txtIDReview.Text));
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Thông Báo", "Có lỗi xảy ra trong quá trình xét duyệt mẫu tin !" + ex);
            }
        }
        protected void btnUnReviewWindow_Click(object sender, DirectEventArgs e)
        {
            try
            {
                var objCheckIsUsed = new EtOrder { Order_Id = int.Parse(txtIDReview.Text) };
                BllOrder.GetOrderCheck(objCheckIsUsed);
                if (objCheckIsUsed.Msg == 0)
                {
                    HTML.clsFormat.Alert_ERROR("Lỗi", "Có chứng từ liên quan,không thể thay đổi trạng thái xét duyệt !");
                }
                else
                {
                    var obj = new EtOrderDetail
                    {
                        Order_Id = int.Parse(txtIDReview.Text),
                        IsActive = false,
                        Users_Id_Review = int.Parse(Session["Users_Id"].ToString())
                    };
                    BllOrder.Review(obj);
                    HTML.clsFormat.Alert_INFO("Thông Báo", "Huỷ xét duyệt đơn hàng thành công !");
                    GetOrder();
                    GetOrderReview(int.Parse(txtIDReview.Text));
                    GetOrderSum(int.Parse(txtIDReview.Text));
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Thông Báo", "Có lỗi xảy ra trong quá trình xét duyệt mẫu tin !" + ex);
            }
        }
        protected void btnReLoadReviewOrder_Click(object sender, DirectEventArgs e)
        {
            GetOrder();
            GetOrderEdit(int.Parse(txtIDReview.Text));
            GetOrderSum(int.Parse(txtIDReview.Text));
        }
        protected void btnExitReviewOrder_Click(object sender, DirectEventArgs e)
        {
            WindowOrderReview.Close();
        }
        //Double-Click
        protected void OrderDblClick(object sender, DirectEventArgs e)
        {
            _flag = false;
            txtOrderCode.ReadOnly = true;
            btnRefreshOrderCode.Disable(true);
            int Order_Id = int.Parse(e.ExtraParams["Order_Id"]);
            GetOrderEdit(Order_Id);
            GetOrderSum(Order_Id);
            WindowsOrder.Show();
        }
        //Cell-Click
        protected void CellOrderCustomer_Click(object sender, DirectEventArgs e)
        {
            var sm = grCustomerOrder.GetSelectionModel() as CellSelectionModel;
            if (sm != null)
            {
                string id = sm.SelectedCell.RecordID;
                GetCustomerEdit(int.Parse(id));
                sm.Clear();
                sm.UpdateSelection();
            }
            WindowCustomerOrder.Close();
        }
        //Cell-Update
        protected void UpdateMaterials_Click(object sender, DirectEventArgs e)
        {
            var GetOrder_Detail = e.ExtraParams["grOrder_Detail"];
            var dtgrOrder_Detail = JSON.Deserialize<DataTable>(GetOrder_Detail);
            foreach (DataRow rows in dtgrOrder_Detail.Rows)
            {
                var obj = new EtOrder { Order_Id = int.Parse(rows["Order_Id"].ToString()) };
                BllOrder.GetOrderCheck(obj);
                if (obj.Msg == 0)
                {
                    HTML.clsFormat.Alert_ERROR("Lỗi", "Có chứng từ liên quan,không thể thay đổi được !");
                }
                else
                {
                    var _obj = new EtOrder { Order_Id = int.Parse(rows["Order_Id"].ToString()) };
                    BllOrder.GetOrderCheckReview(_obj);
                    if (_obj.Msg == 0)
                    {
                        HTML.clsFormat.Alert_ERROR("Lỗi", "Thông tin đã được xét duyệt,không thể thay đổi được !");
                    }
                    else
                    {
                        UpdateQuanlity(int.Parse(rows["Order_Detail_Id"].ToString()),
                        int.Parse(rows["Order_Detail_Quality"].ToString()),
                        float.Parse(rows["Order_Detail_Price"].ToString()),
                        float.Parse(rows["Order_Detail_CK_Percent"].ToString()),
                        float.Parse(rows["Order_Detail_VAT_Percent"].ToString()));
                    }
                }
            }
        }
        protected void UpdateOrderReview_Click(object sender, DirectEventArgs e)
        {
            var GetOrder_Detail = e.ExtraParams["grOrderReview"];
            var dtgrOrder_Detail = JSON.Deserialize<DataTable>(GetOrder_Detail);
            foreach (DataRow rows in dtgrOrder_Detail.Rows)
            {
                var obj = new EtOrder { Order_Id = int.Parse(rows["Order_Id"].ToString()) };
                BllOrder.GetOrderCheck(obj);
                if (obj.Msg == 0)
                {
                    HTML.clsFormat.Alert_ERROR("Lỗi", "Có chứng từ liên quan,không thể thay đổi được !");
                }
                else
                {
                    var _obj = new EtOrder { Order_Id = int.Parse(rows["Order_Id"].ToString()) };
                    BllOrder.GetOrderCheckReview(_obj);
                    if (_obj.Msg == 0)
                    {
                        HTML.clsFormat.Alert_ERROR("Lỗi", "Thông tin đã được xét duyệt,không thể thay đổi được !");
                    }
                    else
                    {
                        UpdateQuanlityOrderReview(int.Parse(rows["Order_Detail_Id"].ToString()),
                        int.Parse(rows["Order_Detail_Quality"].ToString()),
                        float.Parse(rows["Order_Detail_Price"].ToString()),
                        float.Parse(rows["Order_Detail_CK_Percent"].ToString()),
                        float.Parse(rows["Order_Detail_VAT_Percent"].ToString()));
                    }
                }
            }
        }
        //Select-Box
        protected void SelectBoxReview_Change(object sender, DirectEventArgs e)
        {
            GetOrder();
        }
        protected void SelectBoxIsUsed_Change(object sender, DirectEventArgs e)
        {
            GetOrderFillterIsUsed();
        }
        //Search
        protected void Search_Event(object sender, DirectEventArgs e)
        {
            var _clsGetOrder = new BllOrder();
            var _dtSearch = _clsGetOrder.GetOrder(txtSearch.Text);
            if (_dtSearch != null && _dtSearch.Rows.Count > 0)
            {
                StoreOrder.DataSource = _dtSearch;
                StoreOrder.DataBind();
            }
            else
            {
                grOrder.GetStore().RemoveAll();
            }
        }
        #endregion

         #region[Method]
        private void GetOrder()
        {
            if (String.IsNullOrEmpty(SelectBoxReview.Text))
            {
                var _clsGetOrder = new BllOrder();
                var _dtGetOrder = _clsGetOrder.GetOrder(txtSearch.Text);
                if (_dtGetOrder != null && _dtGetOrder.Rows.Count > 0)
                {
                    StoreOrder.DataSource = _dtGetOrder;
                    StoreOrder.DataBind();
                }
                else
                {
                    grOrder.GetStore().RemoveAll();
                }
            }
            else
            {
                var _clsGetOrder = new BllOrder();
                var _dtGetOrder = _clsGetOrder.GetOrderActive(string.Empty, int.Parse(SelectBoxReview.SelectedItem.Value));
                if (_dtGetOrder != null && _dtGetOrder.Rows.Count > 0)
                {
                    StoreOrder.DataSource = _dtGetOrder;
                    StoreOrder.DataBind();
                }
                else
                {
                    grOrder.GetStore().RemoveAll();
                }
            }
        }
        private void GetOrderFillterIsUsed()
        {
            if (String.IsNullOrEmpty(SelectBoxIsUsed.Text))
            {
                var _clsGetOrder = new BllOrder();
                var _dtGetOrder = _clsGetOrder.GetOrder(txtSearch.Text);
                if (_dtGetOrder != null && _dtGetOrder.Rows.Count > 0)
                {
                    StoreOrder.DataSource = _dtGetOrder;
                    StoreOrder.DataBind();
                }
                else
                {
                    grOrder.GetStore().RemoveAll();
                }
            }
            else
            {
                var _clsGetOrder = new BllOrder();
                var _dtGetOrder = _clsGetOrder.GetOrderFillterIsUsed(string.Empty, int.Parse(SelectBoxIsUsed.SelectedItem.Value));
                if (_dtGetOrder != null && _dtGetOrder.Rows.Count > 0)
                {
                    StoreOrder.DataSource = _dtGetOrder;
                    StoreOrder.DataBind();
                }
                else
                {
                    grOrder.GetStore().RemoveAll();
                }
            }
        }
        private void GetOrderEdit(int id)
        {
            var _clsGetOrderEdit = new BllOrder();
            var _dtGetOrder = _clsGetOrderEdit.GetOrderDetailEdit(id, 0);
            var _obj = new EtOrder { Order_Id = id };
            BllOrder.GetOrderCheckReview(_obj);
            var obj = new EtOrder { Order_Id = id };
            BllOrder.GetOrderCheck(obj);
            if (obj.Msg == 0)
            {
                btnSavePopUp.Disable(true);
                btnAddCustomer.Disable(true);
                btnAddMaterial.Disable(true);
                btnDelMaterial.Disable(true);
            }
            else if (_obj.Msg == 0)
            {
                btnSavePopUp.Disable(true);
                btnAddCustomer.Disable(true);
                btnAddMaterial.Disable(true);
                btnDelMaterial.Disable(true);
            }
            else
            {
                btnSavePopUp.Enable(true);
                btnAddCustomer.Enable(true);
                btnAddMaterial.Enable(true);
                btnDelMaterial.Enable(true);
            }
            if (_dtGetOrder != null && _dtGetOrder.Rows.Count > 0)
            {
                txtOrder_ID.Text = _dtGetOrder.Rows[0]["Order_Id"].ToString();
                txtOrderCode.Text = _dtGetOrder.Rows[0]["Order_Code"].ToString();
                txtDateBegin.Text = _dtGetOrder.Rows[0]["Order_Date"].ToString();
                txtCustomerID.Text = _dtGetOrder.Rows[0]["Customer_Id"].ToString();
                txtCustomerAlias.Text = _dtGetOrder.Rows[0]["Customer_Alias"].ToString();
                txtCustomerName.Text = _dtGetOrder.Rows[0]["Customer_Name"].ToString();
                txtCustomerAddress.Text = _dtGetOrder.Rows[0]["Customer_Address"].ToString();
                txtDateBeginPay.Text = _dtGetOrder.Rows[0]["Order_DateBegin"].ToString();
                txtDateEndPay.Text = _dtGetOrder.Rows[0]["Order_DateEnd"].ToString();
                txtPaymentDate.Text = _dtGetOrder.Rows[0]["Order_Payment_Date"].ToString();
                txtTaxCode.Text = _dtGetOrder.Rows[0]["Order_TaxCode"].ToString();
                txtDescription.Text = _dtGetOrder.Rows[0]["Order_Note"].ToString();
                StoreOrder_Detail.DataSource = _dtGetOrder;
                StoreOrder_Detail.DataBind();
            }
            else
            {
                grOrder_Detail.GetStore().RemoveAll();
            }
        }
        private void GetOrderSum(int id)
        {
            var _clsGetOrderEdit = new BllOrder();
            var _dtGetOrder = _clsGetOrderEdit.GetOrderDetailSum(id, 0);
            if (_dtGetOrder != null && _dtGetOrder.Rows.Count > 0)
            {
                lbQualityWithOrder.Text = _dtGetOrder.Rows[0]["TotalMaterial"].ToString();
                lbPriceWithOrder.Text = String.Format("{0:0,00}", _dtGetOrder.Rows[0]["TotalPrice"]).Replace(".", ",");
                lbPriCKWithOrder_Total.Text = String.Format("{0:0,00}", _dtGetOrder.Rows[0]["TotalCK"]).Replace(".", ",");
                lbPriVATWithOrder.Text = String.Format("{0:0,00}", _dtGetOrder.Rows[0]["TotalVAT"]).Replace(".", ",");
                lbTotalCostOrderWithOrder.Text = String.Format("{0:0,00}", _dtGetOrder.Rows[0]["TotalALL"]).Replace(".", ",");
                lbTotalMaterialReview.Text = String.Format("{0:0,00}", _dtGetOrder.Rows[0]["TotalALL"]).Replace(".", ",");
            }
        }
        private void GetOrderReview(int id)
        {
            var obj = new EtOrder { Order_Id = id };
            var _obj = new EtOrder { Order_Id = id };
            BllOrder.GetOrderCheckReview(_obj);
            BllOrder.GetOrderCheck(obj);
            if (obj.Msg == 0)
            {
                btnReviewWindow.Disable(true);
                btnUnReviewWindow.Disable(true);
                btnAddMaterial.Disable(true);
                btnDelMaterial.Disable(true);
            }
            else if (_obj.Msg == 0)
            {
                btnReviewWindow.Disable(true);
                btnUnReviewWindow.Disable(true);
                btnAddMaterial.Disable(true);
                btnDelMaterial.Disable(true);
            }
            else
            {
                btnSavePopUp.Enable(true);
                btnAddCustomer.Enable(true);
                btnAddMaterial.Enable(true);
                btnDelMaterial.Enable(true);
            }
            var _clsGetOrderReview = new BllOrder();
            var _dtGetOrderReview = _clsGetOrderReview.GetOrderDetailEdit(id, 0);
            if (_dtGetOrderReview != null && _dtGetOrderReview.Rows.Count > 0)
            {
                try
                {
                    txtIDReview.Text = _dtGetOrderReview.Rows[0]["Order_Id"].ToString();
                    lbReviewCustomer_Alias.Text = _dtGetOrderReview.Rows[0]["Customer_Alias"].ToString();
                    lbReviewCustomer_Name.Text = _dtGetOrderReview.Rows[0]["Customer_Name"].ToString();
                    lbReviewOrderCode.Text = _dtGetOrderReview.Rows[0]["Order_Code"].ToString();
                    lbReviewOrderDate.Text = String.Format("{0:dd-MM-yyyy}", _dtGetOrderReview.Rows[0]["Order_DateBegin"]);
                    if ((bool)_dtGetOrderReview.Rows[0]["IsActiveOrder"])
                    {
                        btnReviewWindow.Disable(true);
                        btnUnReviewWindow.Enable(true);

                        lbReViewTime.IconCls = "x-icon-tick";
                        lbReviewDateUpdate.IconCls = "x-icon-tick";
                    }
                    if ((bool)_dtGetOrderReview.Rows[0]["IsActiveOrder"] == false)
                    {
                        btnReviewWindow.Enable(true);
                        btnUnReviewWindow.Enable(true);

                        lbReViewTime.IconCls = "x-icon-cross";
                        lbReviewDateUpdate.IconCls = "x-icon-cross";
                    }
                    if (_dtGetOrderReview.Rows[0]["DateReview"].ToString() == string.Empty ||
                        _dtGetOrderReview.Rows[0]["DateReview"].ToString() == DBNull.Value.ToString())
                    {
                        lbReviewDateUpdate.Text = "N/A";
                    }
                    else
                    {
                        lbReviewDateUpdate.Text = String.Format("{0:dd-MM-yyyy}", _dtGetOrderReview.Rows[0]["DateReview"]);
                    }
                    if (_dtGetOrderReview.Rows[0]["DateReview"].ToString() == string.Empty ||
                        _dtGetOrderReview.Rows[0]["DateReview"].ToString() == DBNull.Value.ToString())
                    {
                        lbReViewTime.Text = "N/A";
                    }
                    else
                    {
                        lbReViewTime.Text = String.Format("{0:HH:mm:ss}", _dtGetOrderReview.Rows[0]["DateReview"]);
                    }
                    //End
                    StoreOrderReview.DataSource = _dtGetOrderReview;
                    StoreOrderReview.DataBind();
                }
                catch (Exception ex)
                {
                    HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
                }
            }
            else
            {
                grOrderReview.GetStore().RemoveAll();
            }
        }
        private void GetOrderDetailTemp()
        {
            var _clsGetOrderEdit = new BllOrder();
            var _dtGetOrder = _clsGetOrderEdit.GetOrderDetailEditTmep(1, int.Parse(Session["Users_Id"].ToString()));
            if (_dtGetOrder != null && _dtGetOrder.Rows.Count > 0)
            {
                StoreOrder_Detail.DataSource = _dtGetOrder;
                StoreOrder_Detail.DataBind();
            }
            else
            {
                grOrder_Detail.GetStore().RemoveAll();
            }
        }
        private void GetOrderDetailTempSum()
        {
            var _clsGetOrderEdit = new BllOrder();
            var _dtGetOrder = _clsGetOrderEdit.GetOrderDetailEditTmepSum(1, int.Parse(Session["Users_Id"].ToString()));
            if (_dtGetOrder != null && _dtGetOrder.Rows.Count > 0)
            {
                lbQualityWithOrder.Text = _dtGetOrder.Rows[0]["TotalMaterial"].ToString();
                lbPriceWithOrder.Text = String.Format("{0:0,00}", _dtGetOrder.Rows[0]["TotalPrice"]).Replace(".", ",");
                lbPriCKWithOrder_Total.Text = String.Format("{0:0,00}", _dtGetOrder.Rows[0]["TotalCK"]).Replace(".", ",");
                lbPriVATWithOrder.Text = String.Format("{0:0,00}", _dtGetOrder.Rows[0]["TotalVAT"]).Replace(".", ",");
                lbTotalCostOrderWithOrder.Text = String.Format("{0:0,00}", _dtGetOrder.Rows[0]["TotalALL"]).Replace(".", ",");
            }
        }
        private void GetMaterials()
        {
            var _clsMaterials = new Materials_BLL();
            var _dtMaterials = _clsMaterials.GetMaterials();
            if (_dtMaterials != null && _dtMaterials.Rows.Count > 0)
            {
                StoreMaterial.DataSource = _dtMaterials;
                StoreMaterial.DataBind();
            }
            else
            {
                grMaterial.GetStore().RemoveAll();
            }
        }
        private void GetCustomer()
        {
            var _clsCustomer = new Customer_BLL();
            var _dtCustomer = _clsCustomer.BindGirdtb_Customer(string.Empty);
            if (_dtCustomer != null && _dtCustomer.Rows.Count > 0)
            {
                StoreCustomerOrder.DataSource = _dtCustomer;
                StoreCustomerOrder.DataBind();
            }
            else
            {
                grCustomerOrder.GetStore().RemoveAll();
            }
        }
        private void GetCustomerEdit(int id)
        {
            var _clsCustomer = new Customer_BLL();
            var _dtCustomerEdit = _clsCustomer.GetCustomerDetail(id);
            if (_dtCustomerEdit != null && _dtCustomerEdit.Rows.Count > 0)
            {
                txtCustomerID.Text = _dtCustomerEdit.Rows[0]["Customer_ID"].ToString();
                txtCustomerAlias.Text = _dtCustomerEdit.Rows[0]["Customer_Alias"].ToString();
                txtCustomerName.Text = _dtCustomerEdit.Rows[0]["Customer_Name"].ToString();
                txtCustomerAddress.Text = _dtCustomerEdit.Rows[0]["Customer_Address"].ToString();
                txtTaxCode.Text = _dtCustomerEdit.Rows[0]["Customer_Contract_Tax_Code"].ToString();
            }
        }
        private void GetOrderFillterDate()
        {
            if (String.IsNullOrEmpty(txtDateBeginFillter.Text) && String.IsNullOrEmpty(txtDateEndFillter.Text))
            {
                var _clsGetOrder = new BllOrder();
                var _dtGetOrder = _clsGetOrder.GetOrder(txtSearch.Text);
                if (_dtGetOrder != null && _dtGetOrder.Rows.Count > 0)
                {
                    StoreOrder.DataSource = _dtGetOrder;
                    StoreOrder.DataBind();
                }
                else
                {
                    grOrder.GetStore().RemoveAll();
                }
            }
            else
            {
                var _clsGetOrder = new BllOrder();
                var _dtGetOrder = _clsGetOrder.GetOrderFillterDate(txtDateBeginFillter.Text, txtDateEndFillter.Text);
                if (_dtGetOrder != null && _dtGetOrder.Rows.Count > 0)
                {
                    StoreOrder.DataSource = _dtGetOrder;
                    StoreOrder.DataBind();
                }
                else
                {
                    grOrder.GetStore().RemoveAll();
                }
            }
        }
        private void GetAutoID()
        {
            var _clsBllCreateCode = new BllCreateCode();
            var _dtGetAutoID = _clsBllCreateCode.GetAutoID("Order_Code", "tb_Order");
            if (_dtGetAutoID != null && _dtGetAutoID.Rows.Count > 0)
            {
                try
                {
                    txtOrderCode.Text = "DTHM-" + DateTime.Now.ToString("yyMM") + "-000" +
                                            Convert.ToString(int.Parse(_dtGetAutoID.Rows[0]["Auto_ID"].ToString()) +
                                                             int.Parse(1.ToString()));
                }
                catch (Exception ex)
                {
                    HTML.clsFormat.Alert_ERROR("Thông Báo", ex.Message);
                }
            }
        }
        private bool CheckInsert()
        {
            bool check = false;
            var _clsCheck = new BllOrder();
            var _dtCheck = _clsCheck.GetOrder(txtSearch.Text);
            if (_dtCheck != null && _dtCheck.Rows.Count > 0)
            {
                foreach (DataRow dr in _dtCheck.Rows)
                {
                    if (txtOrderCode.Text == dr["Order_Code"].ToString())
                    {
                        check = true;
                    }
                }
            }
            return check;
        }
        private bool CheckInsertDetail(int Materials_Id)
        {
            bool check = false;
            var _clsCheck = new BllOrder();
            var _dtCheck = _clsCheck.GetOrderDetailEditTmep(1, int.Parse(Session["Users_Id"].ToString()));
            if (_dtCheck != null && _dtCheck.Rows.Count > 0)
            {
                foreach (DataRow dr in _dtCheck.Rows)
                {
                    if (Materials_Id == int.Parse(dr["Materials_Id"].ToString()))
                    {
                        check = true;
                    }
                }
            }
            return check;
        }
        private void Insert()
        {
            if (_flag)
            {
                InsertValue();
            }
            else
            {
                if (CheckPermisstionDobclick())
                {
                    HTML.clsFormat.Alert_ERROR("Lỗi", "Bạn không được cấp phép thay đổi dữ liệu !");
                }
                else
                {
                    UpdateValue();
                }
            }
        }
        private void InsertValue()
        {
            try
            {
                if (CheckInsert())
                {
                    HTML.clsFormat.Alert_ERROR("Lỗi", "Chứng từ này đã tồn tại !");
                }
                else
                {
                    var _clsGetOrderEdit = new BllOrder();
                    var _dtGetOrder = _clsGetOrderEdit.GetOrderDetailEditTmep(1,
                        int.Parse(Session["Users_Id"].ToString()));
                    if (_dtGetOrder.Rows.Count < 0)
                    {
                        HTML.clsFormat.Alert_ERROR("Lỗi", "Vui lòng chọn vật tư để thêm mới !");
                    }
                    else
                    {
                        var obj = new EtOrder
                        {
                            Order_Code = txtOrderCode.Text,
                            Order_TaxCode = txtTaxCode.Text,
                            Order_Date = DateTime.Parse(txtDateBegin.Text),
                            Customer_Id = int.Parse(txtCustomerID.Text),
                            Order_DateBegin = DateTime.Parse(txtDateBeginPay.Text),
                            Order_DateEnd = DateTime.Parse(txtDateEndPay.Text),
                            Order_Payment_Date = DateTime.Parse(txtPaymentDate.Text),
                            Order_Transport = 0,
                            Order_Note = txtDescription.Text,
                            Order_VAT = 0,
                            Order_Total = 0,
                            Order_Total_Payment = 0,
                            IsActive = false,
                            Users_Id = int.Parse(Session["Users_Id"].ToString())
                        };
                        BllOrder.Insert(obj);
                        HTML.clsFormat.Alert_INFO("Thông Báo", "Thêm mới thành công !");
                        GetOrder();
                        ClearText();
                    }
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void UpdateValue()
        {
            var obj = new EtOrder
            {
                Order_Id = int.Parse(txtOrder_ID.Text),
                Order_TaxCode = txtTaxCode.Text,
                Order_Note = txtDescription.Text
            };
            BllOrder.Update(obj);
            HTML.clsFormat.Alert_INFO("Thông Báo", "Cập nhật thành công !");
            GetOrder();
        }
        private void InsertDetail()
        {
            try
            {
                var sm = grMaterial.GetSelectionModel() as CheckboxSelectionModel;
                if (sm != null)
                    foreach (var row in sm.SelectedRows)
                    {
                        if (CheckInsertDetail(int.Parse(row.RecordID)))
                        {
                            HTML.clsFormat.Alert_ERROR("Lỗi", "Vật tư này đã tồn tại !");
                        }
                        else
                        {
                            var obj = new EtOrderDetail
                            {
                                Order_Id = null,
                                Materials_Id = int.Parse(row.RecordID),
                                Order_Detail_Quality = 0,
                                Order_Detail_Price = 0,
                                Order_Detail_CK_Percent = 0,
                                Order_Detail_CK = 0,
                                Order_Detail_VAT_Percent = 0,
                                Order_Detail_VAT = 0,
                                Order_Detail_Total_Price = 0,
                                Order_Detail_Note = string.Empty,
                                IsActive = false,
                                Users_Id = int.Parse(Session["Users_Id"].ToString()),
                                Flag = 1
                            };
                            BllOrder.InsertDetail(obj);
                            HTML.clsFormat.Alert_INFO("Thông Báo", "Thêm mới vật tư thành công");
                        }
                    }
                GetOrderDetailTemp();
                GetOrderDetailTempSum();
                WindowMaterial.Close();
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void UdpateDetail()
        {
            try
            {
                var sm = grMaterial.GetSelectionModel() as CheckboxSelectionModel;
                if (sm != null)
                    foreach (var row in sm.SelectedRows)
                    {
                        if (CheckInsertDetail(int.Parse(row.RecordID)))
                        {
                            HTML.clsFormat.Alert_ERROR("Lỗi", "Vật tư này đã tồn tại !");
                        }
                        else
                        {
                            var obj = new EtOrderDetail
                            {
                                Order_Id = int.Parse(txtOrder_ID.Text),
                                Materials_Id = int.Parse(row.RecordID),
                                Order_Detail_Quality = 0,
                                Order_Detail_Price = 0,
                                Order_Detail_CK_Percent = 0,
                                Order_Detail_CK = 0,
                                Order_Detail_VAT_Percent = 0,
                                Order_Detail_VAT = 0,
                                Order_Detail_Total_Price = 0,
                                Order_Detail_Note = string.Empty,
                                IsActive = false,
                                Users_Id = int.Parse(Session["Users_Id"].ToString()),
                                Flag = 0
                            };
                            BllOrder.InsertDetail(obj);
                            HTML.clsFormat.Alert_INFO("Thông Báo", "Thêm mới vật tư thành công");
                        }
                    }
                GetOrderEdit(int.Parse(txtOrder_ID.Text));
                GetOrderSum(int.Parse(txtOrder_ID.Text));
                WindowMaterial.Close();
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void UpdateQuanlity(int Order_Detail_Id, int Order_Detail_Quality, float Order_Detail_Price, float Order_Detail_CK_Percent,
            float Order_Detail_VAT_Percent)
        {
            try
            {
                var obj = new EtOrderDetail
                {
                    Order_Detail_Id = Order_Detail_Id,
                    Order_Detail_Quality = Order_Detail_Quality,
                    Order_Detail_Price = Order_Detail_Price,
                    Order_Detail_CK_Percent = Order_Detail_CK_Percent,
                    Order_Detail_VAT_Percent = Order_Detail_VAT_Percent
                };
                BllOrder.UpdateQuanlity(obj);
                if (_flag)
                {
                    GetOrderDetailTemp();
                    GetOrderDetailTempSum();
                }
                else
                {
                    GetOrderEdit(int.Parse(txtOrder_ID.Text));
                    GetOrderSum(int.Parse(txtOrder_ID.Text));
                }
                HTML.clsFormat.Alert_INFO("Thông Báo", "Cập nhật thành công !");
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.ToString());
            }
        }
        private void UpdateQuanlityOrderReview(int Order_Detail_Id, int Order_Detail_Quality, float Order_Detail_Price, float Order_Detail_CK_Percent,
            float Order_Detail_VAT_Percent)
        {
            try
            {
                var obj = new EtOrderDetail
                {
                    Order_Detail_Id = Order_Detail_Id,
                    Order_Detail_Quality = Order_Detail_Quality,
                    Order_Detail_Price = Order_Detail_Price,
                    Order_Detail_CK_Percent = Order_Detail_CK_Percent,
                    Order_Detail_VAT_Percent = Order_Detail_VAT_Percent
                };
                BllOrder.UpdateQuanlity(obj);
                if (_flag)
                {
                    GetOrderDetailTemp();
                    GetOrderDetailTempSum();
                }
                else
                {
                    //GetOrderEdit(int.Parse(txtIDReview.Text));
                    //GetOrderSum(int.Parse(txtIDReview.Text));
                    GetOrderReview(int.Parse(txtIDReview.Text));
                    GetOrderSum(int.Parse(txtIDReview.Text));
                }
                HTML.clsFormat.Alert_INFO("Thông Báo", "Cập nhật thành công !");
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.ToString());
            }
        }
        private void DeleteDetail(int Order_Detail_Id, int Flag)
        {
            try
            {
                var obj = new EtOrderDetail { Order_Detail_Id = Order_Detail_Id, Flag = Flag };
                BllOrder.DeleteDetail(obj);
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void DeleteAdd(int Users_Id, int Flag)
        {
            try
            {
                var obj = new EtOrderDetail { Users_Id = Users_Id, Flag = Flag };
                BllOrder.DeleteAdd(obj);
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        #endregion

        #region[ClearText]
        private void ClearText()
        {
            FormPanelOrder.Reset();
            DeleteAdd(int.Parse(Session["Users_Id"].ToString()), 1);
            txtOrder_ID.Text = string.Empty;
            lbQualityWithOrder.Text = string.Empty;
            lbPriceWithOrder.Text = string.Empty;
            lbPriCKWithOrder_Total.Text = string.Empty;
            lbPriVATWithOrder.Text = string.Empty;
            lbTotalCostOrderWithOrder.Text = string.Empty;
            grOrder_Detail.GetStore().RemoveAll();
        }
        #endregion

        #region[Permisstion]
        private void CheckPermisstion()
        {
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.Order, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnAdd == false)
                {
                    btnAddNew.Visible = false;
                }
                if (Is_BtnEdit == false)
                {
                    btnEdit.Visible = false;
                }
                if (Is_BtnView == false)
                {
                    PanelMainOrder.Visible = false;
                }
                if (Is_BtnDel == false)
                {
                    btnDel.Visible = false;
                }
                if (Is_BtnPrint == false)
                {
                    btnExport.Visible = false;
                }
                if (Is_BtnReview == false)
                {
                    btnReview.Visible = false;
                }
                if (Is_BtnCancel == false)
                {
                    btnCancelPopUp.Visible = false;
                }
            }
        }
        private bool CheckPermisstionDobclick()
        {
            bool check = false;
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.Order, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnEdit == false)
                {
                    check = true;
                }
            }
            return check;
        }
        #endregion
    }
}